<template>
  <div class="school-clubs">
    <div class="section-header">
      <h2 class="section-title">社团管理</h2>
      <el-button type="primary" @click="openCreateDialog">创建社团</el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索社团名称"
        class="search-input"
        clearable
        @input="filterClubs"
      >
        <template #prefix>
          <i class="el-icon-search"></i>
        </template>
      </el-input>
    </div>

    <!-- 社团列表 -->
    <el-table
      v-loading="loading"
      :data="filteredClubs"
      style="width: 100%"
      stripe
      row-key="_id"
      empty-text="暂无社团数据"
    >
      <el-table-column prop="clubimg" label="社徽" width="80">
        <template #default="scope">
          <img
            :src="scope.row.clubimg ? `http://localhost:5000/uploads/${scope.row.clubimg}` : defaultImg"
            class="club-logo"
          />
        </template>
      </el-table-column>

      <el-table-column prop="clubname" label="社团名称" min-width="150">
        <template #default="scope">
          <el-link @click="goToClubPage(scope.row._id)" type="primary">{{ scope.row.clubname }}</el-link>
        </template>
      </el-table-column>

      <el-table-column prop="description" label="社团简介" min-width="200" show-overflow-tooltip></el-table-column>

      <el-table-column prop="memberCount" label="成员数" width="90">
        <template #default="scope">
          {{ getMemberCount(scope.row) }}
        </template>
      </el-table-column>

      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="editClub(scope.row)"
          >编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="confirmDissolve(scope.row)"
          >解散</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, total"
        :total="totalClubs"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 创建/编辑社团对话框 -->
    <el-dialog
      :title="isEdit ? '编辑社团' : '创建社团'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="clubForm" :rules="clubRules" ref="clubFormRef" label-width="100px">
        <el-form-item label="社团名称" prop="clubname">
          <el-input v-model="clubForm.clubname" placeholder="请输入社团名称"></el-input>
        </el-form-item>

        <el-form-item label="社团简介" prop="description">
          <el-input type="textarea" v-model="clubForm.description" placeholder="请输入社团简介" :rows="4"></el-input>
        </el-form-item>

        <el-form-item label="社团校徽">
          <div class="logo-upload">
            <div class="preview-container">
              <img
                v-if="previewUrl"
                :src="previewUrl"
                alt="社团校徽预览"
                class="logo-preview"
              >
              <div v-else class="logo-placeholder">
                <i class="el-icon-picture-outline"></i>
                <span>校徽预览</span>
              </div>
            </div>

            <el-upload
              class="upload-container"
              action="#"
              :http-request="uploadLogo"
              :show-file-list="false"
              accept="image/jpeg,image/png,image/gif"
            >
              <el-button type="primary">{{ clubForm.clubimg ? '更换校徽' : '上传校徽' }}</el-button>
              <div class="upload-tip">推荐上传正方形图片，最大支持2MB</div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveClub" :loading="saving">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
const defaultImg = '/src/assets/shehui.png'
const props = defineProps({
  schoolId: {
    type: String,
    required: true
  }
})

const router = useRouter()

// 表格数据
const clubs = ref([])
const filteredClubs = ref([])
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalClubs = ref(0)

// 表单数据
const clubFormRef = ref(null)
const dialogVisible = ref(false)
const isEdit = ref(false)
const previewUrl = ref('')
const saving = ref(false)
const clubForm = ref({
  _id: null,
  clubname: '',
  description: '',
  clubimg: null,
  clubimgFile: null
})

// 表单验证规则
const clubRules = {
  clubname: [
    { required: true, message: '请输入社团名称', trigger: 'blur' },
    { min: 2, max: 50, message: '社团名称长度应在2-50个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '简介长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 监听schoolId变化，重新加载数据
watch(() => props.schoolId, (newValue) => {
  if (newValue) {
    fetchClubs()
  }
})

// 获取社团列表
const fetchClubs = async () => {
  if (!props.schoolId) return

  loading.value = true
  try {
    const response = await axios.get(`http://localhost:5000/schools/${props.schoolId}/clubs`, {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    })

    if (response.data && response.data.clubs) {
      clubs.value = response.data.clubs
      filteredClubs.value = response.data.clubs
      totalClubs.value = response.data.pagination.total
    } else {
      clubs.value = []
      filteredClubs.value = []
      totalClubs.value = 0
    }
  } catch (error) {
    console.error('获取社团列表失败:', error)
    ElMessage.error('获取社团列表失败')
  } finally {
    loading.value = false
  }
}

// 筛选社团
const filterClubs = () => {
  if (!searchQuery.value) {
    filteredClubs.value = clubs.value
  } else {
    const query = searchQuery.value.toLowerCase()
    filteredClubs.value = clubs.value.filter(club =>
      club.clubname.toLowerCase().includes(query) ||
      (club.description && club.description.toLowerCase().includes(query))
    )
  }
}

// 获取成员数量
const getMemberCount = (club) => {
  return club.members ? club.members.length : 0
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchClubs()
}

// 打开创建社团对话框
const openCreateDialog = () => {
  isEdit.value = false
  resetClubForm()
  dialogVisible.value = true
}

// 编辑社团
const editClub = (club) => {
  isEdit.value = true
  previewUrl.value = club.clubimg ? `http://localhost:5000/uploads/${club.clubimg}` : ''

  clubForm.value = {
    _id: club._id,
    clubname: club.clubname,
    description: club.description || '',
    clubimg: club.clubimg || null,
    clubimgFile: null
  }

  dialogVisible.value = true
}

// 确认解散社团
const confirmDissolve = (club) => {
  ElMessageBox.confirm(
    `确定要解散社团 "${club.clubname}" 吗？此操作不可逆，将删除该社团的所有数据。`,
    '解散社团',
    {
      confirmButtonText: '确定解散',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    dissolveClub(club._id)
  }).catch(() => {
    // 用户取消操作
  })
}

// 解散社团（调用后端API）
const dissolveClub = async (clubId) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
        ElMessage.warning('请先登录')
        return
    }
    await axios.delete(`http://localhost:5000/clubs/${clubId}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    ElMessage.success('社团已成功解散')
    fetchClubs() // 刷新列表
  } catch (error) {
    console.error('解散社团失败:', error)
    ElMessage.error('解散社团失败: ' + (error.response?.data?.message || error.message))
  }
}

// 处理校徽上传
const uploadLogo = async (options) => {
  const file = options.file

  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过2MB')
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    previewUrl.value = e.target.result
  }
  reader.readAsDataURL(file)

  clubForm.value.clubimgFile = file
}

// 重置社团表单
const resetClubForm = () => {
  clubForm.value = {
    _id: null,
    clubname: '',
    description: '',
    clubimg: null,
    clubimgFile: null
  }
  previewUrl.value = ''

  if (clubFormRef.value) {
    clubFormRef.value.resetFields()
  }
}

// 保存社团（创建或更新）
const saveClub = () => {
  clubFormRef.value.validate(async (valid) => {
    if (!valid) return

    saving.value = true

    try {
      const token = localStorage.getItem('token')
      if (!token) {
          ElMessage.warning('请先登录')
          saving.value = false
          return
      }

      const formData = new FormData()
      formData.append('clubname', clubForm.value.clubname)
      formData.append('description', clubForm.value.description)
      if (clubForm.value.clubimgFile) {
        formData.append('clubimg', clubForm.value.clubimgFile)
      }

      let response
      if (isEdit.value && clubForm.value._id) {
        // 编辑模式：调用 PUT 请求
        response = await axios.put(
          `http://localhost:5000/clubs/${clubForm.value._id}`,
          formData,
          {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'multipart/form-data'
            }
          }
        )
        ElMessage.success('社团更新成功')
      } else {
        // 创建模式：调用 POST 请求
        formData.append('school', props.schoolId) // 创建时需要关联学校
        response = await axios.post(
          'http://localhost:5000/clubs',
          formData,
          {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'multipart/form-data'
            }
          }
        )
        ElMessage.success('社团创建成功')
      }

      dialogVisible.value = false
      fetchClubs() // 刷新列表
    } catch (error) {
      console.error('保存社团失败:', error)
      ElMessage.error('保存社团失败: ' + (error.response?.data?.message || error.message))
    } finally {
      saving.value = false
    }
  })
}

// 跳转到社团页面
const goToClubPage = (clubId) => {
  router.push(`/club/${clubId}`)
}

// 组件挂载时获取社团列表
onMounted(() => {
  if (props.schoolId) {
    fetchClubs()
  }
})
</script>

<style scoped>
.school-clubs {
  padding: 20px 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  color: #fff;
  font-size: 24px;
  margin: 0;
}

.filter-container {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.club-logo {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

/* 对话框样式 */
.logo-upload {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.preview-container {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #1f1b24;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #555;
}

.logo-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.logo-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
}

.logo-placeholder i {
  font-size: 30px;
  margin-bottom: 5px;
}

.upload-container {
  flex: 1;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

/* Element Plus 组件样式重写 */
:deep(.el-table) {
  background-color: transparent;
  color: #eee;
}

:deep(.el-table th) {
  background-color: #1f1b24;
  color: #b0bec5;
  border-bottom-color: #333;
}

:deep(.el-table tr) {
  background-color: #28232e;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #23202a;
}

:deep(.el-table td) {
  border-bottom-color: #333;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #342e3d;
}

:deep(.el-input__inner), :deep(.el-textarea__inner) {
  background-color: #1f1b24;
  border-color: #444;
  color: #fff;
}

:deep(.el-input__inner:focus), :deep(.el-textarea__inner:focus) {
  border-color: #00aeff;
}

:deep(.el-dialog) {
  background-color: #28232e;
  border-radius: 10px;
}

:deep(.el-dialog__title) {
  color: #fff;
}

:deep(.el-dialog__body) {
  color: #b0bec5;
}

:deep(.el-form-item__label) {
  color: #b0bec5;
}

:deep(.el-button) {
  margin-left: 10px;
}

:deep(.el-table__empty-text) {
  color: #777;
}
</style>
